// var API_SERVER_URL = 'https://www.scdf56.com';
var API_SERVER_URL = 'http://localhost:8080';
// var API_SERVER_URL = 'http://101.207.248.146:18090';

var API_UCENTER_USER_REG = API_SERVER_URL + '/reg';
var API_UCENTER_USER = API_SERVER_URL + '/user';
var API_UCENTER_USER_PAGE = API_SERVER_URL + '/user/page';
var API_UCENTER_USER_LOGIN = API_SERVER_URL + '/user/login';
var API_UCENTER_ROLE = API_SERVER_URL + '/role';
var API_UCENTER_ROLE_PAGE = API_SERVER_URL + '/role/page';

var API_UCENTER_DRIVER = API_SERVER_URL + '/driver';
var API_CAR = API_SERVER_URL + '/car';
var API_DATA = API_SERVER_URL + '/data';
var API_WAYBILL = API_SERVER_URL + '/waybill';
var API_GOODS = API_SERVER_URL + '/goods';
var API_COMPANY = API_SERVER_URL + '/company';
var API_MEMBER = API_SERVER_URL + '/admin/member';
var API_CAR_LOCATION = API_SERVER_URL + '/location';
var API_ADMIN_HOME = API_SERVER_URL + '/admin/home';
var API_ADMIN_ADDRESS_BOOK = API_SERVER_URL + '/address/book';
var API_REPORT = API_SERVER_URL + '/report';
var API_EXT_API = API_SERVER_URL + '/external';
var ctx;

$(document).ready(function () {
    ctx = $('#base').val();

    var account = getUserAccount();
    if (account != null) {
        $('[data-field="account-name"]').text(account.nickname);
    }

});

var ajaxOption = {
    headers: {
        access_token: getToken()
    },
    error: function (jqXHR) {
        if (jqXHR.status === 403) {
            location.href = '/';
        } else {
            bootbox.alert(jqXHR.responseJSON.message);
        }
    }
};

$.httpclient = {
    ajax: function (method, url, data, func) {
        showLoading();
        $.ajax({
            type: method,
            url: url,
            dataType: "json",
            contentType: 'application/json',
            headers: {
                access_token: getToken()
            },
            data: data,
            success: func,
            error: function (jqXHR) {
                console.info(jqXHR);
                if (jqXHR.status === 403) {
                    location.href = '/';
                } else {
                    bootbox.alert(jqXHR.responseJSON.message);
                }
            },
            complete: function () {
                loadingDialog.modal("hide");
            }
        });
    },
    get: function (url, data, func) {
        this.ajax('get', url, data, func);
    },
    post: function (url, data, func) {
        this.ajax('post', url, data, func);
    },
    put: function (url, data, func) {
        this.ajax('put', url, data, func);
    },
    delete: function (url, data, func) {
        this.ajax('delete', url, data, func);
    }
};

var tokenKey = 'token';
var userAccountKey = 'user_account';

function saveUserAccount(user) {
    localStorage.setItem(userAccountKey, user);
}

function removeUserAccount() {
    localStorage.removeItem(userAccountKey);
}

function getUserAccount() {
    return JSON.parse(localStorage.getItem(userAccountKey));
}

function saveToken(token) {
    localStorage.setItem(tokenKey, token);
}

function removeToken() {
    localStorage.removeItem(tokenKey);
}

function getToken() {
    return localStorage.getItem(tokenKey);
}

function showDriverStatusName(value) {
    switch (value) {
        case 'UN_CHECK':
            return '待审核';
        case 'IDLE':
            return '空闲';
        case 'DISABLE':
            return '禁用';
        case 'WORKING':
            return '运输';
        case 'REST':
            return '休息';
        default:
            return '错误';
    }
}

function showCarTypeName(value) {
    switch (value) {
        case 'LARGE_CAR':
            return '重型货车';
        case 'MEDIUM_CAR':
            return '中型货车';
        case 'SMALL_CAR':
            return '轻型货车';
        case 'MINI_CAR':
            return '微型货车';
        case 'TRAILER':
            return '挂车';
        default:
            return '错误';
    }
}

function showCarBoxTypeName(value) {
    switch (value) {
        case 'FLAT':
            return '平板';
        case 'SEMI_TRAILER':
            return '半挂';
        case 'BARRIER':
            return '栏板';
        case 'FULLY_ENCLOSED':
            return '全封闭';
        case 'SEMI_CLOSED':
            return '半封闭';
        default:
            return '错误';
    }
}

function showWaybillStatusName(value) {
    switch (value) {
        case 'CREATED':
            return '创建中';
        case 'WAIT_PICK':
            return '待接单';
        case 'PICKED':
            return '已接单';
        case 'IN_TRANSIT':
            return '运输中';
        case 'ARRIVALS':
            return '到达';
        case 'WAIT_PAY':
            return '待支付';
        case 'DONE':
            return '完成';
        case 'CANCEL':
            return '取消';
        default:
            return '错误';
    }
}

function showWaybillTypeName(value) {
    switch (value) {
        case 'PUBLIC':
            return '公共订单';
        case 'DIRECT':
            return '定向订单';
        default:
            return '错误';
    }
}

function showAcceptedStateName(value) {
    switch (value) {
        case 'ACCEPTED':
            return '已接单';
        case 'REJECT':
            return '拒绝';
        case 'STANDBY':
            return '等待回应';
        default:
            return '错误';
    }
}

var loadingDialog;

function showLoading(title) {
    if (!loadingDialog) {
        loadingDialog = bootbox.dialog({
            title: title,
            message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>'
        })
    } else {
        loadingDialog.modal("show");
    }

}

function fullField(data) {
    for (var key in data) {
        var item = $('[data-field="' + key + '"]');
        if (item) {
            var target = item.data('field-target');
            var value = data[key];
            if (typeof value === 'object') {
                fullChildField(value, key);
            } else if (target === 'img' && value) {
                item.attr('src', $('#base').val() + '/file/image/' + value);
            } else if (target === 'enum' && value) {
                var func = item.data('convert-func');
                item.text(eval(func + '("' + value + '")'));
            } else {
                item.text(data[key]);
            }

        }
    }
}

function fullChildField(data, clazz) {
    if (clazz) {
        var obj = {};
        for (var key in data) {
            obj[clazz + '.' + key] = data[key];
        }
        fullField(obj);
    }

}

function fullForm(dataForm, data) {

    dataForm.find('input,select').each(function () {
        var value = data[this.name];
        if (value) {
            var tagName = this.tagName;
            if (tagName === 'INPUT') {
                $(this).val(value);
            } else if (tagName === 'SELECT') {
                $(this).selectpicker('val', value);
            }
        }
    });
}

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length === 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};

function isVehicleNumber(vehicleNumber) {
    var result = false;
    if (vehicleNumber.length === 7) {
        var express = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
        result = express.test(vehicleNumber);
    }
    return result;
}

function checkPhone(phone) {
    return !(/^1[3456789]\d{9}$/.test(phone))
}

function checkIdCard(idCard) {
    var id = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/;
    return !(id.test(idCard));

}
